package com.foreveross.chameleon.mdm;

import android.app.Application;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import com.foreveross.chameleon.base.PushApplication;
import com.foreveross.chameleon.utils.AppLog;
import org.apache.cordova.App;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Objects;

/**
 * 安装配置文件
 * Created by wzq on 14-11-13.
 */
public class InstallConfig {
    // private static final String TAG = InstallConfig.class.getSimpleName();

    private DevicePolicyManager dPM;
    private ComponentName adminName;

    InstallConfig() {
        Application app = PushApplication.getApplication();
        dPM = (DevicePolicyManager) app.getSystemService(Context.DEVICE_POLICY_SERVICE);
        adminName = new ComponentName(app, BslDeviceAdmin.class);
    }

    private boolean isActive() {
        return dPM.isAdminActive(adminName);
    }

    /**
     * 从string中，读取 & 执行配置
     *
     * @param jsonConfig json形式的配置文件,string类型
     */
    public void exe(String jsonConfig) throws Exception {
        AppLog.i("----处理config----");
        // check
        if (!isActive()) {
            AppLog.e("mdm not active");
            return;
        }

        JSONObject json = null;
        try {
            json = converToJson(jsonConfig);
        } catch (JSONException e) {
            // e.printStackTrace();
            AppLog.e("jsonConfig 格式不合法,不能->JSON:\n" + e.toString());
            throw e;
        }

        // test
        AppLog.i("----检测config----");
        Iterator<String> testKeys = json.keys();
        while (testKeys.hasNext()) {
            try {
                String key = testKeys.next();
                Object value = json.get(key);
                AppLog.i(key + "=" + value);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        // 将json解释为mdm命令
        AppLog.i("----执行config----");
        Iterator<String> keys = json.keys();
        MdmCmdExecutor executor = MdmCmdExecutor.getInstance();
        while (keys.hasNext()) {
            String key = keys.next();
            String value = null;
            try {
                value = json.getString(key);
                ModelMdmCmd aCmd = convertToCmd(key, value);
                if (aCmd != null) {
                    boolean state = executor.exec(aCmd);
                    if (!state) {
                        AppLog.e("mdm 执行失败");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                AppLog.e("mdm 执行异常,清检测机器是否支持该 mdm操作:key=" + key + ",value=" + value);
                e.printStackTrace();
            }
        }
    }

    /**
     * 转化为json,符合模板
     */
    private JSONObject converToJson(String jsonConfig) throws JSONException {
        JSONObject jsonIn = new JSONObject(jsonConfig);
        JSONObject jsonOut = new JSONObject();
        JSONArray payloadContent = jsonIn.getJSONArray("PayloadContent");
        for (int i = 0; i < payloadContent.length(); i++) {
            JSONObject subItem = payloadContent.getJSONObject(i);
            String name = subItem.getString("PayloadDisplayName");

            if ("Restrictions".equals(name)) {
                collect(subItem, jsonOut, KEY_CAMERA);
            }
            //
            else if ("Passcode".equals(name)) {
                collect(subItem, jsonOut, KEY_PASSWORD);
            }

        }
        return jsonOut;
    }

    private static final String[] KEY_CAMERA = new String[]{"allowCamera"};
    private static final String[] KEY_PASSWORD = new String[]
            {"minComplexChars",              // 最小特殊字符数
                    "maxInactivity",                // 屏幕超时
                    "requireAlphanumeric",          // 密码必须包含字母 数字
                    "maxPINAgeInDays",              // 密码过期时间 in days
                    "pinHistory",                   // 新密码不得与上｛1｝次的任一密码重复
                    "maxFailedAttempts",            // 密码尝试次数
                    "minLength",                    // 最小长度
                    //"allowSimple",                  // 简单密码 no api
                    //"forcePIN"                      // 必须用密码 no api
            };

    /**
     * 收集mdm描述
     *
     * @throws JSONException
     */
    private void collect(JSONObject srcJson, JSONObject dstJson, String[] keys)
            throws JSONException {

        for (String key : keys) {
            if (srcJson.has(key)) {
                Object value = srcJson.get(key);
                // value => String
                if (value instanceof Number) {
                    value = "" + value;
                } else if (value instanceof Boolean) {
                    value = ((Boolean) value) ? "true" : "false";
                }
                AppLog.v("key=" + key + "value=" + value);
                dstJson.put(key, value);
            }
        }
    }

    private ModelMdmCmd convertToCmd(String key, String value) {
        ModelMdmCmd cmd = new ModelMdmCmd();
        if ("allowCamera".equals(key)) {//allowCamera=false
            if ("true".equals(value) || "false".equals(value)) {
                cmd.cmdType = MdmCmdType.camera_disable;
                cmd.cmdArg = "true".equals(value) ? "false" : "true";
            }
        } else if ("minComplexChars".equals(key)) {
            if (!"".equals(value)) {
                cmd.cmdType = MdmCmdType.password_min_symbol;
                cmd.cmdArg = value;
            }
        } else if ("maxInactivity".equals(key)) {
            if (!"".equals(value)) {
                cmd.cmdType = MdmCmdType.timeout_screen;
                int min = Integer.parseInt(value);
                int ms = min * 60 * 1000;
                cmd.cmdArg = "" + ms;
            }
        } else if ("requireAlphanumeric".equals(key)) {
            if ("true".equals(value)) {
                cmd.cmdType = MdmCmdType.password_quality;
                cmd.cmdArg = MdmCmdExecutor.alpha_digit;
            }
        } else if ("maxPINAgeInDays".equals(key) && !"".equals(value)) {
            if (!"".equals(value)) {
                cmd.cmdType = MdmCmdType.password_expire_time;
                int days = Integer.parseInt(value);
                int ms = days * 24 * 60 * 60 * 1000;
                cmd.cmdArg = "" + ms;
            }
        } else if ("pinHistory".equals(key)) {
            if (!"".equals(value)) {
                cmd.cmdType = MdmCmdType.password_history_restrict;
                cmd.cmdArg = value;
            }
        } else if ("maxFailedAttempts".equals(key)) {
            if (!"".equals(value)) {
                cmd.cmdType = MdmCmdType.password_max_fail;
                cmd.cmdArg = value;
            }
        } else if ("minLength".equals(key)) {
            if (!"".equals(value)) {
                cmd.cmdType = MdmCmdType.password_min_len;
                cmd.cmdArg = value;
            }
        }
//        else if ("forcePIN".equals(key)) {
//            if ("true".equals(value)) {
//                cmd.cmdType = MdmCmdType.password_require;
//                cmd.cmdArg = value;
//            }
//        }
        else {
            AppLog.e("未识别的key=" + key);
        }

        return cmd.cmdType != null ? cmd : null;
    }
}
